package com.hrbxlh.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hrbxlh.actionImpl.HomeworkTestActionImpl;
import com.hrbxlh.util.PubMethods;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.SourceActionImpl;


/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：SourceAction.java
* Description：成绩action类
* History：
* Date           Author               Desc
* 2017.3.29		  sy                   建立
* -------------------------------------------------------
*/

@Controller
public class SourceAction {
	
	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;

	@Autowired
	@Qualifier("homeworkTestActionImpl")
	private HomeworkTestActionImpl homeworkTestActionImpl;

	//日志信息
	Logger logger = Logger.getLogger(MemberAction.class.getName());
	


	/*
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表（教师）页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllSourceList", method = RequestMethod.POST)
	public void getAllSourceList(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			/*模拟参数开始*/
			/*Map<String, Object> mapUse = new HashMap<String, Object>();
			mapUse.put("pageNow", 1);
			mapUse.put("pageSize", 10);
			jsonStr = mapper.writeValueAsString(mapUse);*/
			/*模拟参数结束*/
			logger.info("学生成绩列表（教师）页面的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取人员列表信息
			Map<String, Object> resultAllMap = sourceActionImpl.getAllSourceList(preParamMap,session,request);
			if(preParamMap.get("classId")!=null||preParamMap.get("courseId")!=null||preParamMap.get("classEndMark")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("classId", preParamMap.get("classId"));
				searchObejct.put("courseId", preParamMap.get("courseId"));
				searchObejct.put("classEndMark", preParamMap.get("classEndMark"));
				resultMap.put("searchObejct", searchObejct);
			}
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			//返回值
			resultMap.put("memberList", resultAllMap.get("memberList"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("classList", resultAllMap.get("classList"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("学生成绩列表（教师）页面出现异常", e);

		} finally {
			logger.info("学生成绩列表（教师）页面的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}

	/*
	 * @param classId
	 * @return  通过班级id获取某班级下所属课程
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllCourseListByClassId", method = RequestMethod.POST)
	public void getAllCourseListByClassId(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			logger.info("通过班级id获取某班级下所属课程的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//通过班级id获取某班级下所属课程
			Map<String, Object> resultAllMap = sourceActionImpl.getAllCourseListByClassId(preParamMap,session,request);
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			//返回值
			resultMap.put("courseList", resultAllMap.get("courseList"));
		} catch (Exception e) {
			resultMap.put("errMsg", "通过班级id获取某班级下所属课程失败");
			e.printStackTrace();
			logger.error("通过班级id获取某班级下所属课程出现异常", e);

		} finally {
			logger.info("通过班级id获取某班级下所属课程的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}

	/**
	 * 导入学生成绩
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/imStuSoruce", method=RequestMethod.POST)
	public void imStuSoruce(@RequestParam("file") CommonsMultipartFile file, HttpServletResponse response, HttpServletRequest request,HttpSession session) throws Exception {
		 String fileName =  file.getOriginalFilename();
		 String view ="";
		 String reJsonStr = "";
		 ObjectMapper mapper = new ObjectMapper();
		 Map<String,Object> map = new HashMap<String,Object>();
		 try{
			  logger.info("导入学生成绩的参数为："+file);
			 //获取文件后缀
			 String allFileName=file.getName();
			 String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			 if(!prefix.equals("xls")){
				 map.put("flag","fail");
				 map.put("msg","请将文件改为excel2003版");
				 return;
			 }
			  String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);// 存放位置
			  File destFile = new File(path);
			  String file1 = String.valueOf(destFile);
			  FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			  Map<String,Object> sourceMap = sourceActionImpl.imStuSoruce(file1,session,request);
			  boolean flag = (Boolean) sourceMap.get("flag");
			  String msg = flag ==true?"学生导入成绩成功":String.valueOf(sourceMap.get("msg")) ;
			  map.put("flag",flag);
			  map.put("msg",msg);
			 //将临时存到文件删除
			 PubMethods.delTempFile(fileName);

		 }catch(Exception e){
			e.printStackTrace();
			map.put("msg", "数据填写不正确，导入学生成绩失败");
			e.printStackTrace();
			logger.error("导入学生成绩", e);
			
		 }finally{
			 logger.info("导入学生成绩的返回结果为："+map);
			PubMethods.postMed(response,mapper,map);
		 }
	}
	
	/**
	 * 
	 * @return 查询成绩设置。
	 * @throws IOException
	 */
	/*@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProWedith", method = RequestMethod.GET)
	public ModelAndView getProWedith(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			

			//获取成绩设置信息
			Map<String, Object> resultAllMap = sourceActionImpl.getProWedith(session,resultMap);
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//返回值
			resultMap.put("sorceMap", resultAllMap.get("sorceMap"));
			//未结课的类表
			resultMap.put("courseList", resultAllMap.get("courseList"));
		    //人员列表页面名称
			pageName = "pc/sourceSet";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("成绩设置异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}*/

	/**
	 *
	 * @return 查询成绩设置。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProWedith", method = RequestMethod.POST)
	public void getProWedith(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {

			logger.info("查询成绩设置的参数为："+jsonStr);
			resultMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取成绩设置信息
			Map<String, Object> resultAllMap = sourceActionImpl.getProWedith(session,resultMap,request);
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			//返回值
			resultMap.put("sorceMap", resultAllMap.get("sorceMap"));
			//未结课的类表
			resultMap.put("courseList", resultAllMap.get("courseList"));

		} catch (Exception e) {
			resultMap.put("errMsg", "查询成绩设置失败");
			e.printStackTrace();
			logger.error("查询成绩设置异常", e);

		} finally {
			logger.info("查询成绩设置的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 *
	 * @return 获得当前登录人未结课课程列表。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getCourseNoEndListByTeaIdByPost", method = RequestMethod.POST)
	public void getCourseNoEndListByTeaIdByPost(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			logger.info("获得当前登录人未结课课程列表的参数为："+jsonStr);
			Map<String,Object> paramMap = mapper.readValue(jsonStr,resultMap.getClass());
			//获得当前登录人未结课课程列表
			Map<String, Object> resultAllMap = sourceActionImpl.getCourseNoEndListByTeaId(session,paramMap,request);
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			//未结课的类表
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			if(paramMap.get("courseName")!=null||paramMap.get("courseName")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("courseName", paramMap.get("courseName"));
				/*if(Integer.parseInt(String.valueOf(paramMap.get("courseId")))!=0){
					searchObejct.put("courseId",paramMap.get("courseId"));
				}*/
				resultMap.put("searchObejct", searchObejct);
			}
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");

		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("获取当前登录人未结课课程列表异常", e);
		} finally {
			logger.info("获得当前登录人未结课课程列表的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 *param courseId
	 * @return 获得当前登录人某课成绩设置和权重设置。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getSourceSetByTeaIdOrCourseIdByPost", method = RequestMethod.POST)
	public void getSourceSetByTeaIdOrCourseIdByPost(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> returnMap = new HashMap<String,Object>();

		try {
			logger.info("获得当前登录人未结课课程列表的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取成绩设置信息
			Map<String, Object> resultAllMap = sourceActionImpl.getProWedith(session,preParamMap,request);
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			resultMap.put("sorceMap", resultAllMap.get("sorceMap"));
		} catch (Exception e) {
			resultMap.put("errMsg", "获取当前登录人某课权重和评分设置");
			e.printStackTrace();
			logger.error("获取当前登录人某课权重和评分设置", e);
		} finally {
			logger.info("获得当前登录人未结课课程列表的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}

	/**
	 * @param request coureseId
	 * @param response
	 * @return  成绩设置。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addSorceSet", method = RequestMethod.POST)
	public void addSorceSet(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			logger.info("成绩设置的参数为："+jsonStr);
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//成绩设置。
			Map<String,Object> map = sourceActionImpl.addSorceSet(paramMap,session,request);
			boolean resultFlag = (Boolean) map.get("flag");
			if(resultFlag){
				//如果是优良中差类型,修改分数
				if(Integer.parseInt(paramMap.get("souceMark").toString()) == 0){
					boolean falg = homeworkTestActionImpl.saveTaskAndExamPerformaceDegree(paramMap, session,request);
					if(falg){
						resultMark = (resultFlag) ? "success" : "fail";
						resultMap.put("result", resultMark);
						resultMap.put("errMsg", map.get("errMsg"));
					}else{
						resultMap.put("result", "fail");
						resultMap.put("errMsg", "性质新的方法出错了");
					}
				}
			}
			resultMark = (resultFlag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("errMsg", map.get("errMsg"));
		} catch (Exception e) {
			resultMap.put("errMsg", "设置失败");
			e.printStackTrace();
			logger.error("成绩设置出现异常addSorceSet", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("成绩设置的返回结果为addSorceSet："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/**
	 * @return  学生成绩详情
	 * @throws IOException
	 */
	/*@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getStuSourceDetail", method = RequestMethod.GET)
	public ModelAndView getStuSourceDetail(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取成绩详情信息
			Map<String, Object> resultAllMap = sourceActionImpl.getStuSourceDetail(preParamMap,session);
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//返回值
			resultMap.put("detailMap", resultAllMap.get("detailMap"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
		    //人员列表页面名称
			pageName = "pc/sourceDetail";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转学生成绩详情页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}*/

	/**
	 * @return  学生成绩详情
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getStuSourceDetail", method = RequestMethod.POST)
	public void getStuSourceDetail(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			logger.info("学生成绩详情的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取成绩详情信息
			Map<String, Object> resultAllMap = sourceActionImpl.getStuSourceDetail(preParamMap,session);
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/
			//返回值
			resultMap.put("detailMap", resultAllMap.get("detailMap"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("userName", resultAllMap.get("userName"));

		} catch (Exception e) {
			resultMap.put("errMsg", "学生成绩详情失败");
			e.printStackTrace();
			logger.error("学生成绩详情出现异常", e);

		} finally {
			logger.info("学生成绩详情的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}


	/*
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面(学生)。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getStuAllSourceList", method = RequestMethod.POST)
	public void getStuAllSourceList(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			/*模拟参数开始*/
			/*Map<String, Object> mapUse = new HashMap<String, Object>();
			mapUse.put("pageNow", 1);
			mapUse.put("pageSize", 10);
			jsonStr = mapper.writeValueAsString(mapUse);*/
			/*模拟参数结束*/
			logger.info("学生成绩列表页面(学生)的参数为："+jsonStr);
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取人员列表信息
			Map<String, Object> resultAllMap = sourceActionImpl.getStuAllSourceList(preParamMap,session,request);
			if(preParamMap.get("classId")!=null||preParamMap.get("courseId")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("courseId", preParamMap.get("courseId"));
				resultMap.put("searchObejct", searchObejct);
			}
			//查询当前人的消息
			/*List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);*/

			//返回值
			resultMap.put("memberList", resultAllMap.get("memberList"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转学生成绩列表页面出现异常", e);

		} finally {
			logger.info("学生成绩列表页面(学生)的返回结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}
}
